#include "transactioncontroller.h"
#include "transactionmodel.h"
#include "core/itemcontroller.h"

#include <QSqlQuery>
#include <QSqlError>
#include <QDebug>

TransactionController::TransactionController(QObject *parent) :
    BaseController(parent)
{
}

QList<StockModel *> TransactionController::getStocksOf(TransactionModel *transaction)
{
    QSqlQuery query;
    QString sql;
    QList<StockModel *> list;
    StockModel *stock;
    ItemController ctrl;

    sql = "SELECT ID, itemID, serial, actualSellingPrice "
            "FROM Stocks WHERE transactionID = :tID";

    query.prepare(sql);
    query.bindValue(":tID", transaction->getID());

    if (!query.exec()) {
        qDebug() << "TransactionController::getStocksOf() query failed: "
                 << query.lastError().text();
    }

    while (query.next()) {
        stock = new StockModel;
        stock->setID(query.value(0).toInt());
        stock->setItem(ctrl.getItemById(query.value(1).toInt()));
        stock->setSerial(query.value(2).toString());
        stock->setTransaction(transaction);
        stock->setSellPrice(query.value(3).toFloat());

        list.append(stock);
    }

    return list;
}

QList<BaseModel *> TransactionController::getAll()
{
    QList<BaseModel *> list;
    TransactionModel *transaction;
    CustomerModel *customer;
    bool ok;
    QSqlQuery query;
    QString sql = "SELECT t.ID, t.saleDate, t.customerID, t.lastModified,"
            " t.deliveryStatus, t.paymentStatus, t.valid, c.name, c.address, c.contactNumber, "
            " c.notes FROM Transactions AS t LEFT OUTER JOIN Customers AS c"
            " ON t.customerID = c.ID;";

    ok = query.exec(sql);

    if (!ok) {
        qDebug() << "TransactionController::getAll() query failed: "
                 << query.lastError().text();
    }

    while (query.next()) {
        transaction = new TransactionModel;
        customer = new CustomerModel;

        customer->setID(query.value(2).toInt());
        customer->setName(query.value(7).toString());
        customer->setAddress(query.value(8).toString());
        customer->setContactNumber(query.value(9).toString());
        customer->setNote(query.value(10).toString());

        transaction->setID(query.value(0).toInt());
        transaction->setSaleTime(query.value(1).toDateTime());
        transaction->setCustomer(customer);
        transaction->setLastModificationTime(query.value(3).toDateTime());
        transaction->setDeliveryStatus(query.value(4).toString());
        transaction->setPaid(query.value(5).toBool());
        transaction->setValid(query.value(6).toBool());
        transaction->setStocks(this->getStocksOf(transaction));

        list.append(transaction);
    }

    emit update(list);
    return list;
}

QList<BaseModel *> TransactionController::getAllUnpaid()
{
    QSqlQuery query;
    QString sql;
    TransactionModel *transaction;
    CustomerModel *customer;
    QList<BaseModel *> transactions;

    sql = "SELECT t.ID, t.saleDate, t.customerID, t.lastModified, "
            "t.deliveryStatus, t.paymentStatus, c.name, c.contactNumber, "
            "c.notes "
            "FROM Transactions AS t LEFT OUTER JOIN Customers AS c "
            "WHERE t.valid = 1 AND t.paid = 0";
    query.exec(sql);

    while (query.next()) {
        customer = new CustomerModel;
        customer->setID(query.value(2).toInt());
        customer->setName(query.value(6).toString());
        customer->setContactNumber(query.value(7).toString());
        customer->setNote(query.value(8).toString());

        transaction = new TransactionModel;
        transaction->setID(query.value(0).toInt());
        transaction->setSaleTime(query.value(1).toDateTime());
        transaction->setCustomer(customer);
        transaction->setLastModificationTime(query.value(3).toDateTime());
        transaction->setDeliveryStatus(query.value(4).toString());
        transaction->setPaid(query.value(5).toBool());

        transactions.append(transaction);
    }

    return transactions;
}

QList<BaseModel *> TransactionController::getAllUndelivered()
{
    QSqlQuery query;
    QString sql;
    TransactionModel *transaction;
    CustomerModel *customer;
    QList<BaseModel *> transactions;

    sql = "SELECT t.ID, t.saleDate, t.CustomerID, t.lastModified, "
            "t.deliveryStatus, t.paymentStatus, c.name, c.contactNumber, "
            "c.notes "
            "FROM Transactions AS t LEFT OUTER JOIN Customers AS c "
            "WHERE t.valid = 1 AND t.deliveryStatus LIKE 'RECORDED' ";
    query.exec(sql);

    while (query.next()) {
        customer = new CustomerModel;
        customer->setID(query.value(2).toInt());
        customer->setName(query.value(6).toString());
        customer->setContactNumber(query.value(7).toString());
        customer->setNote(query.value(8).toString());

        transaction = new TransactionModel;
        transaction->setID(query.value(0).toInt());
        transaction->setSaleTime(query.value(1).toDateTime());
        transaction->setCustomer(customer);
        transaction->setLastModificationTime(query.value(3).toDateTime());
        transaction->setDeliveryStatus(query.value(4).toString());
        transaction->setPaid(query.value(5).toBool());

        transactions.append(transaction);
    }

    return transactions;
}

void TransactionController::addTransaction(TransactionModel *transaction)
{
    QSqlQuery query;
    bool ok;
    QString sql = "INSERT INTO Transactions"
            " (saleDate, customerID, lastModified, deliveryStatus, paymentStatus, valid)"
            " VALUES (:saleDate, :customerID, :lastModified, :deliveryStatus, "
            ":paymentStatus, :valid);";

    query.prepare(sql);
    query.bindValue(":saleDate", QDateTime::currentDateTime());
    query.bindValue(":lastModified", QDateTime::currentDateTime());
    query.bindValue(":customerID", transaction->getCustomer()->getID());
    query.bindValue(":deliveryStatus", transaction->getDeliveryStatus());
    query.bindValue(":paymentStatus", transaction->isPaid());
    query.bindValue(":valid", transaction->isValid());

    ok = query.exec();

    if (!ok) {
        qDebug() << "TransactionController: Add Transaction failed: "
                    << query.lastError().text();
    }
}
